package com.hsurosy.hsuchain.nft.base.statemachine;

import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.hsurosy.hsuchain.nft.base.exception.BizException;

import java.util.Map;

/**
 * 通用状态机基类
 * @Author Hsu琛君珩
 * @Date 2024-10-04 18:49
 * @Description
 * @Version: v1.0.0
 */
public class BaseStateMachine<STATE, EVENT> implements StateMachine<STATE, EVENT> {

    /**
     * 状态转移映射表
     */
    private Map<String, STATE> stateTransitions = Maps.newHashMap();

    /**
     * 添加状态转移
     *
     * @param origin 原始状态
     * @param event 事件
     * @param target 目标状态
     */
    protected void putTransition(STATE origin, EVENT event, STATE target) {
        stateTransitions.put(Joiner.on("_").join(origin, event), target);
    }

    /**
     * 执行状态转移
     *
     * @param state 当前状态
     * @param event 触发事件
     * @return 目标状态
     * @throws BizException 如果无法找到匹配的状态转移，抛出业务异常
     */
    @Override
    public STATE transition(STATE state, EVENT event) {
        STATE target = stateTransitions.get(Joiner.on("_").join(state, event));
        if (target == null) {
            throw new BizException("state = " + state + " , event = " + event, STATE_MACHINE_TRANSITION_FAILED);
        }
        return target;
    }
}
